package com.wu;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * Hello world!
 *
 */
public class Server{
    public static void main (String[] args) throws IOException {
        ServerSocket ss= new ServerSocket(8080);
        System.out.println("server is running......");
        while(true){
            Socket s = ss.accept();
            System.out.println("connected from "+s.getRemoteSocketAddress());

            Thread t = new Handler(s);
            t.start();
        }
    }
}
class Handler extends Thread {
    Socket s;

    public Handler(Socket s) {
        this.s = s;
    }

    public void run() {
        try (InputStream is = s.getInputStream();//获取请求
             OutputStream os = s.getOutputStream();)//响应请求
        {
            handle(is, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("client disconnected......");
    }

    private void handle(InputStream is, OutputStream os) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));

        boolean request =false;
        String firstLine = br.readLine();
        if(firstLine.startsWith("GET /HTTP/1.")){
            request = true;
        }

        for(;;){
            String header = br.readLine();
            if(header.isEmpty()){
                break;
            }
            System.out.println(header);
        }
        System.out.println(request?"Response OK":"Response Error");
        if(!request){
            bw.write("HTTP/1.0 404 Found\r\n");
            bw.write("Content-Length: 0\r\n");
            bw.write("\r\n");
            bw.flush();
        }else{
            InputStream is1 = Server.class.getClassLoader().getResourceAsStream("html/a.html");
            BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
            StringBuilder data = new StringBuilder();
            String line = null;
        }
    }
}

